import {View, Text, Image} from '@tarojs/components'
import React, {useCallback, useEffect, useRef, useState} from "react";
import {OrderItem} from "@/common/apis/model";
import LogUtils from "@/utils/log";
import {getOrderStatusStyle, OrderStatus} from "@/common/enums";
import Utils from "@/utils/common";
import {Button, Cell, Divider, Empty} from "@antmjs/vantui";
import {SearchPageModel} from "@/pages/order/search_page";
import RouthPath from "@/common/RouthPath";
import {orderCancelApi, orderListApi} from "@/common/apis/home_datasource";
import ShowUtils from "@/utils/show_utils";


definePageConfig({
  navigationBarTitleText: '预约列表'
})

export default function Book_list() {
  const [items, setItems] = useState<OrderItem[]>()
  const params = useRef<SearchPageModel>();

  const getList = useCallback(() => {
    orderListApi("-1").then((res) => {
      setItems(res)
    })
  }, []);

  useEffect(() => {
    const p = Utils.getParamsByRouter(Utils.getI())
    if (p && p.data) {
      params.current = Utils.getObjectWithUrl<SearchPageModel>(p.data)
    }
    orderListApi('-1').then((res) => {
      setItems(res)
    })
    return () => {
      LogUtils.info("Book_list", "Book_list")
    }
  }, []);

  const handleButtons = useCallback((e, item, type) => {
    e.stopPropagation(); // 阻止事件冒泡到父级的 onClick
    if (type === -1) {
      Utils.modal("提示", "确定要取消吗？", true, (ok) => {
        if (ok) {
          orderCancelApi(item.id).then((r) => {
            if (r) {
              Utils.showOkToast("取消成功")
              getList()
            }
          })
        }
      })
    } else if (type === 0) {
      const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
        id: item.id
      })
      Utils.navigateAndListenToEvent(url, "refresh", (data) => {
        getList()
      })
    } else if (type === 1) {
      const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
        id: item.id
      })
      Utils.navigateAndListenToEvent(url, "refresh", (data) => {
        getList()
      })
    }
  }, [getList]);


  const renderActionButtons = useCallback((item) => {
    let buttons = null;
    let cancelButton = (
      <Button style={{marginRight: '10px'}} size='normal' type='info' hairline plain onClick={(e) => {
        handleButtons(e, item, -1);
      }}
      >
        取消
      </Button>
    )
    // 使用枚举值会更清晰和安全
    if (item.status === OrderStatus.WAIT_CONFIRMATION || item.status === OrderStatus.WAIT_PAYMENT) { // 状态为 2
      const isPay = item.status === OrderStatus.WAIT_PAYMENT;
      const btnText = isPay ? '支付' : '确认';
      buttons = (
        <View>
          {cancelButton}
          <Button size='normal' type='info' onClick={(e) => {
            if (isPay) {
              handleButtons(e, item, 0);
            } else {
              handleButtons(e, item, 1);
            }
          }}
          >
            {btnText}
          </Button>
        </View>
      );
    } else if (item.status < OrderStatus.FINISHED) {
      buttons = (
        <View>
          {cancelButton}
        </View>
      )
    }

    if (buttons) {
      return (
        <View>
          <View style={{
            display: 'flex',
            flexDirection: 'row',
            margin: '10px',
            boxSizing: 'border-box',
            justifyContent: 'flex-end',
          }}
          >
            {buttons}
          </View>
          <Divider style={{marginTop: '0px'}} /> {/* 如果按钮存在，Divider 可以在按钮之后 */}
        </View>
      );
    }
    return null; // 如果没有匹配的状态，则不渲染按钮区域
  }, [handleButtons]);

  return (
    <View style={{backgroundColor: 'white'}}>
      {
        items && !Utils.isEmpty(items) ? <View>
          {
            items.map((item, index) => {
              const orderStatusInfo = getOrderStatusStyle(item.status)
              return <View key={index} onClick={() => {
                const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
                  id: item.id
                })
                Utils.navigateAndListenToEvent(url, "refresh", (data) => {
                  getList()
                })
                //传入url 和 doAction(data)
              }}
              >
                <Cell renderIcon={<Text style={{fontSize: '14px'}}>订单号：{item.id}</Text>}
                  renderTitle={<Text
                    style={{
                          color: orderStatusInfo.color,
                          textAlign: 'right',
                          fontSize: '14px',
                          width: '100%',
                          display: 'inline-block',
                        }}
                  >{orderStatusInfo.text}</Text>}

                />
                <View style={{display: 'flex', flexDirection: 'row', padding: '10px 20px', boxSizing: 'border-box'}}>
                  <View>
                    <Image src={item.projectImage} style={{width: '150px', height: '150px'}} mode='aspectFill' />
                  </View>
                  <View
                    style={{marginLeft: '10px', display: 'flex', flexDirection: 'column', flex: 1, height: '150px'}}
                  >
                    <Text>机器：{item.machineName}</Text>
                    <View>
                      <Text>项目：{item.projectName}</Text>
                      {/*{item.note ? <Text style={{color: 'gray',fontSize: '12px'}}>{`(${item.note})`}</Text> : null}*/}
                    </View>
                    <Text>预约时间：{ShowUtils.getShowTime(item.bookAllTimes)}</Text>
                    <View style={{flex: 1, display: 'flex', justifyContent: 'flex-end'}}>
                      <Text style={{
                        fontSize: '16px',
                        color: 'red',
                        textAlign: 'right',
                        marginTop: '10px',
                        alignSelf: 'flex-end'
                      }}
                      >{ShowUtils.getDefaultPrice(item.actualAmount)}</Text>
                      <Text style={{
                        fontSize: '16px',
                        color: 'gray',
                        textAlign: 'right',
                        marginTop: '10px',
                        alignSelf: 'flex-end',
                        textDecoration: 'line-through',
                      }}
                      >{`(${ShowUtils.getDefaultPrice(item.amount)})`}</Text>
                    </View>
                  </View>
                </View>
                <Divider style={{margin: '0px 20px'}} />
                {
                  renderActionButtons(item)
                }
              </View>
            })
          }
        </View> : <Empty description='暂无数据' />
      }
    </View>
  )
}
